# -*- coding: utf-8 -*-
"""converter_mixin
PDF ➜ 图片 功能模块
将 main.py 中 def convert_pdfs_thread(...) 整个方法剪切粘贴到 class ConverterMixin 内。
"""

import os
import traceback
from tkinter import messagebox
import fitz  # PyMuPDF


class ConverterMixin:
    """PDF 转图片相关方法 mixin"""
    def convert_pdfs_thread(self):
        """批量转换PDF文件的线程包装器"""
        try:
            total_files = len(self.pdf_paths)
            output_mode = self.output_mode.get()  # 获取输出模式
            
            for file_index, pdf_path in enumerate(self.pdf_paths):
                pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]

                # 打开PDF文件
                pdf_document = None # Initialize for finally block
                try:
                    pdf_document = fitz.open(pdf_path)
                except Exception as e:
                    print(f"无法打开文件 {pdf_path}: {e}")
                    # 在主线程中显示错误
                    self.after(0, messagebox.showerror, "错误", f"无法打开文件:\\n{os.path.basename(pdf_path)}\\n{e}")
                    continue  # 跳过此文件

                total_pages = pdf_document.page_count

                if total_pages == 1:
                    # --- 单页PDF处理逻辑 ---
                    page_number = 0  # 只有一页，页码为0
                    page = pdf_document[page_number]
                    matrix = fitz.Matrix(self.quality / 72, self.quality / 72)
                    pix = None
                    try:
                        pix = page.get_pixmap(matrix=matrix, alpha=False)  # alpha=False for JPG
                    except Exception as e:
                        print(f"无法获取页面 {page_number + 1} 从 {pdf_path}: {e}")
                        self.after(0, messagebox.showwarning, "警告",
                                   f"无法获取页面 {page_number + 1} 从:\\n{os.path.basename(pdf_path)}\\n{e}")
                        if pdf_document: pdf_document.close()
                        continue  # 跳过此文件 (因为单页PDF的唯一页面处理失败)

                    # 根据输出模式决定文件名和路径
                    if output_mode == "single_folder":
                        output_image_name = f"{pdf_name}.jpg"
                        output_file_path = os.path.join(self.output_path, output_image_name)
                    else:  # separate 模式
                        output_image_name = f"{pdf_name}.jpg"
                        output_file_path = os.path.join(self.output_path, output_image_name)

                    try:
                        pix.save(output_file_path)
                    except Exception as e:
                        print(f"无法保存页面 {page_number + 1} 从 {pdf_path} 到 {output_file_path}: {e}")
                        self.after(0, messagebox.showerror, "错误",
                                   f"无法保存单页PDF图像:\\n{os.path.basename(pdf_path)}\\n到 {output_image_name}\\n{e}")
                        if pdf_document: pdf_document.close()
                        continue  # 跳过此文件 (保存失败)
                    
                    # 更新单页PDF的进度
                    current_file_progress = (file_index + 1) / total_files
                    status_text = f"正在处理: {pdf_name} (单页) -> {output_image_name}"
                    self.after(0, self.update_progress_safe, current_file_progress, status_text)

                else:
                    # --- 多页PDF处理逻辑 ---
                    if output_mode == "single_folder":
                        # 所有图片放入同一个文件夹，文件名包含PDF名称和页码
                        for page_number in range(total_pages):
                            page = pdf_document[page_number]
                            matrix = fitz.Matrix(self.quality / 72, self.quality / 72)
                            pix = None
                            try:
                                pix = page.get_pixmap(matrix=matrix, alpha=False)
                            except Exception as e:
                                print(f"无法获取页面 {page_number + 1} 从 {pdf_path}: {e}")
                                self.after(0, messagebox.showwarning, "警告",
                                           f"无法获取页面 {page_number + 1} 从:\\n{os.path.basename(pdf_path)}\\n{e}")
                                continue  # 跳过此页面

                            # 保存为图片，文件名包含PDF名称
                            output_page_image_name = f"{pdf_name}_page_{page_number + 1}.jpg"
                            output_file_path = os.path.join(self.output_path, output_page_image_name)
                            try:
                                pix.save(output_file_path)
                            except Exception as e:
                                print(f"无法保存页面 {page_number + 1} 从 {pdf_path} 到 {output_file_path}: {e}")
                                self.after(0, messagebox.showerror, "错误",
                                           f"无法保存页面 {page_number + 1} 从:\\n{os.path.basename(pdf_path)}\\n到 {os.path.basename(output_file_path)}\\n{e}")
                                continue  # 暂时继续处理其他页面/文件

                            # 更新进度条 (在主线程中更新UI)
                            total_progress = (file_index + (page_number + 1) / total_pages) / total_files
                            status_text = f"正在处理: {pdf_name} - 第 {page_number + 1}/{total_pages} 页"
                            self.after(0, self.update_progress_safe, total_progress, status_text)
                    else:
                        # 分类存储模式 - 每个PDF创建单独文件夹
                        pdf_output_dir = os.path.join(self.output_path, pdf_name)
                        os.makedirs(pdf_output_dir, exist_ok=True)

                        for page_number in range(total_pages):
                            page = pdf_document[page_number]
                            matrix = fitz.Matrix(self.quality / 72, self.quality / 72)
                            pix = None
                            try:
                                pix = page.get_pixmap(matrix=matrix, alpha=False)
                            except Exception as e:
                                print(f"无法获取页面 {page_number + 1} 从 {pdf_path}: {e}")
                                self.after(0, messagebox.showwarning, "警告",
                                           f"无法获取页面 {page_number + 1} 从:\\n{os.path.basename(pdf_path)}\\n{e}")
                                continue  # 跳过此页面

                            # 保存为图片
                            output_page_image_name = f"page_{page_number + 1}.jpg"
                            output_file_path = os.path.join(pdf_output_dir, output_page_image_name)
                            try:
                                pix.save(output_file_path)
                            except Exception as e:
                                print(f"无法保存页面 {page_number + 1} 从 {pdf_path} 到 {output_file_path}: {e}")
                                self.after(0, messagebox.showerror, "错误",
                                           f"无法保存页面 {page_number + 1} 从:\\n{os.path.basename(pdf_path)}\\n到 {os.path.basename(output_file_path)}\\n{e}")
                                continue  # 暂时继续处理其他页面/文件

                            # 更新进度条 (在主线程中更新UI)
                            total_progress = (file_index + (page_number + 1) / total_pages) / total_files
                            status_text = f"正在处理: {pdf_name} - 第 {page_number + 1}/{total_pages} 页"
                            self.after(0, self.update_progress_safe, total_progress, status_text)
                
                if pdf_document: # 确保在循环的这一点关闭文档
                    pdf_document.close()

            # 所有文件处理完毕后显示成功消息 (在主线程)
            self.after(0, self.show_success_message, "所有PDF转换完成！")

        except Exception as e:
            # 在主线程中显示通用错误消息
            error_details = traceback.format_exc()
            self.after(0, self.show_error_message, f"转换过程中出现错误：{str(e)}\\n{error_details}")

        finally:
            # 在主线程中重置UI状态
            self.after(0, self.reset_ui_state, self.convert_btn, self.progress_bar, self.status_label)
